package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.service.*;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理各种业务异常（地址簿为空、购物车数据为空）
        AddressBook addressBook = addressBookService.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //2.向订单表中插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        User user = userService.getById(addressBook.getUserId());
        String number = UUID.randomUUID().toString();
        orders.setNumber(number);
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(addressBook.getUserId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setUserName(user.getName());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        this.save(orders);

        //3.向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailService.saveBatch(orderDetails);

        //4.清空当前用户的购物车数据
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

        //5. 封装VO返回结果
        return new OrderSubmitVO(orders.getId(), orders.getNumber(), orders.getAmount(), orders.getOrderTime());


    }


    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = new Page<>(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper
                .eq(ordersPageQueryDTO.getStatus() != null, Orders::getStatus, ordersPageQueryDTO.getStatus())
                .eq(ordersPageQueryDTO.getNumber() != null, Orders::getNumber, ordersPageQueryDTO.getNumber())
                .eq(ordersPageQueryDTO.getBeginTime() != null, Orders::getOrderTime, ordersPageQueryDTO.getBeginTime())
                .eq(ordersPageQueryDTO.getEndTime() != null, Orders::getDeliveryTime, ordersPageQueryDTO.getEndTime())
                .eq(ordersPageQueryDTO.getPhone() != null, Orders::getPhone, ordersPageQueryDTO.getPhone())
                .eq(ordersPageQueryDTO.getUserId() != null, Orders::getUserId, ordersPageQueryDTO.getUserId());
        page = this.page(page, ordersLambdaQueryWrapper);
        List<Orders> orders = page.getRecords();
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            orderVO.setOrderDishes(orderDetailList.toString());
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }
        return new PageResult(this.count(), orderVOList);
    }

    @Override
    public PageResult queryHistoryOrders(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        Page<Orders> page1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(status != null, Orders::getStatus, status);
        page1 = this.page(page1, lambdaQueryWrapper);
        List<Orders> records = page1.getRecords();
        List<OrderVO> orderVOList = new ArrayList<>();

        for (Orders orders : records) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);
            orderVO.setOrderDetailList(list);
            orderVO.setOrderDishes(list.toString());
            orderVOList.add(orderVO);
        }
        return new PageResult(this.count(), orderVOList);

    }

    @Override
    public void repetition(Long id) {
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartService.saveBatch(shoppingCartList);
    }

    @Override
    public OrderVO getOrderDetailById(Long id) {
        Orders orders = this.getById(id);
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        orderVO.setOrderDishes(orderDetailList.toString());
        return orderVO;
    }

    @Override
    public void cancelOrderById(Long id) {
        Orders orders = this.getById(id);
        // 校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 校验订单状态
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders1 = new Orders();
        // 订单处于待接单状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //支付状态修改为 退款
            orders1.setPayStatus(Orders.REFUND);
            log.info("用户:{}取消订单，退款成功！！！", BaseContext.getCurrentId());
        }
        // 更新订单状态、取消原因、取消时间

        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason("用户取消");
        orders1.setCancelTime(LocalDateTime.now());
        LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Orders::getId, id);
        this.update(orders1, lambdaUpdateWrapper);
    }

    @Override
    public void payment(OrdersPaymentDTO ordersPaymentDTO) {
        log.info("用户:{}确认订单，支付成功！！！", BaseContext.getCurrentId());
        LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ordersPaymentDTO.getOrderNumber() != null, Orders::getNumber, ordersPaymentDTO.getOrderNumber())
                .set(Orders::getStatus, Orders.TO_BE_CONFIRMED)
                .set(Orders::getPayStatus, Orders.PAID)
                .set(Orders::getCheckoutTime, LocalDateTime.now());
        this.update(lambdaUpdateWrapper);

        //通过websocket向客户端向客户端浏览器推送消息
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(ordersPaymentDTO.getOrderNumber() != null, Orders::getNumber, ordersPaymentDTO.getOrderNumber());
        Orders orders = this.getOne(ordersLambdaQueryWrapper);
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        String toJSONString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(toJSONString);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = this.getById(ordersRejectionDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        log.info("商家由于{}原因拒单，已经向用户成功退款，对你造成的麻烦我们十分的抱歉！！！", ordersRejectionDTO.getRejectionReason());
        Orders newOrders = new Orders();
        newOrders.setStatus(Orders.CANCELLED);
        newOrders.setPayStatus(Orders.REFUND);
        newOrders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        newOrders.setCancelTime(LocalDateTime.now());
        LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ordersRejectionDTO.getId() != null, Orders::getId, ordersRejectionDTO.getId());
        this.update(newOrders, lambdaUpdateWrapper);
    }

    @Override
    public void confirmById(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = this.getById(ordersConfirmDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders newOrders = new Orders();
        newOrders.setStatus(Orders.CONFIRMED);

        LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ordersConfirmDTO.getId() != null, Orders::getId, ordersConfirmDTO.getId());
        this.update(newOrders, lambdaUpdateWrapper);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = this.getById(ordersCancelDTO.getId());
        // 校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 校验订单状态

        // 订单处于已接单状态下取消，需要进行退款
        Orders orders1 = new Orders();
        if (orders.getStatus() == Orders.CONFIRMED || orders.getStatus() == Orders.DELIVERY_IN_PROGRESS) {
            //支付状态修改为 退款
            orders1.setPayStatus(Orders.REFUND);
            log.info("商家由于{}取消订单，退款成功！！！", ordersCancelDTO.getCancelReason());
        }
        // 更新订单状态、取消原因、取消时间

        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason(ordersCancelDTO.getCancelReason());
        orders1.setCancelTime(LocalDateTime.now());
        LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Orders::getId, orders.getId());
        this.update(orders1, lambdaUpdateWrapper);
    }

    @Override
    public OrderStatisticsVO statisticsOrder() {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getStatus, Orders.TO_BE_CONFIRMED);
        Integer toBeConfirmed = Math.toIntExact(this.count(queryWrapper));
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS);
        Integer delivery = Math.toIntExact(this.count(ordersLambdaQueryWrapper));
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getStatus, Orders.CONFIRMED);
        Integer confirmed = Math.toIntExact(this.count(lambdaQueryWrapper));
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(delivery);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

    @Override
    public void delivery(Long id) {
        Orders orders = this.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders newOrders = new Orders();
        newOrders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Orders::getId, id);
        this.update(newOrders, lambdaUpdateWrapper);
    }

    @Override
    public void complete(Long id) {
        Orders orders = this.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders newOrders = new Orders();
        newOrders.setStatus(Orders.COMPLETED);
        newOrders.setDeliveryTime(LocalDateTime.now());
        LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Orders::getId, id);
        this.update(newOrders, lambdaUpdateWrapper);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = this.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //通过websocket向客户端向客户端浏览器推送消息

        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        String toJSONString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(toJSONString);
    }

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        List<BigDecimal> integerList = new ArrayList<>();
        for (LocalDate date : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper.eq(Orders::getStatus, Orders.COMPLETED)
                    .gt(Orders::getOrderTime, beginTime)
                    .lt(Orders::getOrderTime, endTime);
            List<Orders> list = this.list(ordersLambdaQueryWrapper);
            BigDecimal sum = new BigDecimal(0.0);
            if (list != null && list.size() > 0) {
                for (Orders orders : list) {
                    BigDecimal amount = orders.getAmount();
                    sum = sum.add(amount);
                }
            }
            integerList.add(sum);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .turnoverList(StringUtils.join(integerList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper.gt(Orders::getOrderTime, beginTime)
                    .lt(Orders::getOrderTime, endTime);
            Integer orderCount = (int) this.count(ordersLambdaQueryWrapper);

            ordersLambdaQueryWrapper.eq(Orders::getStatus, Orders.COMPLETED);
            Integer validOrderCount = (int) this.count(ordersLambdaQueryWrapper);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        Integer totalOrderCount = new Integer(0);
        Integer validOrderCount = new Integer(0);
        for (Integer orderCount : orderCountList) {
            totalOrderCount = totalOrderCount + orderCount;
        }
        for (Integer validOrder : validOrderCountList) {
            validOrderCount = validOrderCount + validOrder;
        }
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            //计算订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        //运用xml配置文件查询数据库
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.top10(beginTime, endTime);
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }

       /* //orderDetailLambdaQueryWrapper
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.gt(Orders::getOrderTime,beginTime).lt(Orders::getOrderTime,endTime)
                .eq(Orders::getStatus,Orders.COMPLETED);
        List<Orders> list = this.list(ordersLambdaQueryWrapper);
        List<OrderDetail> orderDetails=new ArrayList<>();
        if(list!=null&&list.size()>0){
            for (Orders orders : list) {
                LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderDetailLambdaQueryWrapper
                        .eq(OrderDetail::getOrderId,orders.getId());
                List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
                orderDetailList.addAll(orderDetailList);
            }
        }
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper= new LambdaQueryWrapper<>();
        lambdaQueryWrapper.groupBy(OrderDetail::getName);*/

        return SalesTop10ReportVO.builder()
                .numberList(StringUtils.join(numberList, ","))
                .nameList(StringUtils.join(nameList, ","))
                .build();
    }

    @Override
    public BusinessDataVO queryBusinessData(LocalDateTime beginTime,LocalDateTime endTime) {

        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.gt(Orders::getOrderTime, beginTime)
                .lt(Orders::getOrderTime, endTime);
        Integer totalOrder = (int) this.count(ordersLambdaQueryWrapper);
        ordersLambdaQueryWrapper.eq(Orders::getStatus, Orders.COMPLETED);
        //营业额
        Double turnover = new Double(0.0);
        //有效订单数
        Integer vaildOrder = (int) this.count(ordersLambdaQueryWrapper);
        List<Orders> ordersList = this.list(ordersLambdaQueryWrapper);
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                turnover = turnover + orders.getAmount().doubleValue();
            }
        }
        Double orderCompletionRate = new Double(0.0);
        //订单完成率
        if (totalOrder != null) {
            orderCompletionRate = vaildOrder.doubleValue() / totalOrder;
        }
        //平均客单价
        Double unitPrice = turnover / vaildOrder;
        //新增用户数
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.gt(User::getCreateTime, beginTime)
                .lt(User::getCreateTime, endTime);
        Integer newUser = (int) userService.count(userLambdaQueryWrapper);
        return BusinessDataVO.builder()
                .newUsers(newUser)
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(vaildOrder)
                .unitPrice(unitPrice)
                .turnover(turnover)
                .build();

    }

    @Override
    public OrderOverViewVO queryOrderOverViewVO() {
        //待接单数量
        Integer waitingOrders = getCount(Orders.TO_BE_CONFIRMED);

        //待派送数量
        Integer deliveredOrders = getCount(Orders.CONFIRMED);

        //已完成数量
        Integer completedOrders = getCount(Orders.COMPLETED);

        //已取消数量
        Integer cancelledOrders = getCount(Orders.CANCELLED);

        //全部订单
        Integer allOrders = getCount(null);
        return OrderOverViewVO.builder()
                .waitingOrders(waitingOrders)
                .deliveredOrders(deliveredOrders)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .allOrders(allOrders)
                .build();
    }

    private Integer getCount(Integer status) {
        //获得当天的开始时间
        LocalDateTime beginTime = LocalDateTime.now().with(LocalTime.MIN);
        //获得当天的结束时间
        LocalDateTime endTime = LocalDateTime.now().with(LocalTime.MAX);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(Orders::getOrderTime, beginTime)
                .lt(Orders::getOrderTime, endTime)
                .eq(status != null, Orders::getStatus, status);
        Integer result = (int) this.count(queryWrapper);
        return result;
    }

}
